<!-- shopForCustomer.html (修改商品添加部分) -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>我的店铺管理</title>
  <!--引入的vue.js-->
  <script src="../../js/vue.js"></script>
  <!--引入elementUI的css-->
  <link type="text/css" rel="stylesheet" href="../../css/index.css">
  <!--引入elementUI的js-->
  <script src="../../js/index.js"></script>
  <!--引入axios.js-->
  <script src="../../js/axios.min.js"></script>

  <style>
    .app-container {
      padding: 20px;
    }
    .search-bar {
      margin-bottom: 20px;
    }
    .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 30px;
    }
    .image-slot i {
      font-size: 20px;
    }
    /* 商品选择对话框样式补充 */
    .product-select-dialog .el-dialog__body {
      padding: 20px;
      max-height: 500px;
      overflow-y: auto;
    }
    .product-item {
      display: flex;
      align-items: center;
      padding: 10px;
      border-bottom: 1px solid #f2f2f2;
    }
    .product-item:last-child {
      border-bottom: none;
    }
    .product-info {
      margin-left: 15px;
      flex: 1;
    }
    .product-name {
      font-weight: 500;
      margin-bottom: 5px;
    }
    .product-desc {
      font-size: 12px;
      color: #666;
    }
    .my-shop-header {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
    }
    .my-shop-header h2 {
      margin: 0;
      display: inline-block;
    }
    .status-badge {
      margin-left: 10px;
      vertical-align: middle;
    }
  </style>

</head>
<body>
<div class="app-container">
  <!-- Vue应用根元素 -->
  <div id="app">
    <!-- 审核状态信息面板 -->
    <div v-if="myShopInfo && myShopInfo.auditStatus !== '1'" class="audit-info-card">
      <el-card>
        <div class="audit-status">
          <span v-if="myShopInfo.auditStatus === '0'">审核状态：</span>
          <el-tag v-if="myShopInfo.auditStatus === '0'" type="warning">待审核</el-tag>
          <el-tag v-else-if="myShopInfo.auditStatus === '2'" type="danger">已拒绝</el-tag>
        </div>

        <div v-if="myShopInfo.auditStatus === '0'" class="audit-detail">
          <p>您的店铺正在等待管理员审核，请耐心等待。</p>
          <p>通常审核会在1-2个工作日内完成。</p>
        </div>

        <div v-else-if="myShopInfo.auditStatus === '2'" class="audit-detail">
          <p>您的店铺审核未通过，原因：{{ myShopInfo.auditRemark || '未提供具体原因' }}</p>
          <p>请修改店铺信息后重新提交审核。</p>
        </div>

        <div v-if="myShopInfo.auditTime" class="audit-detail">
          提交时间：{{ myShopInfo.createTime ? myShopInfo.createTime.replace('T', ' ').substring(0, 19) : '' }}
        </div>
      </el-card>
    </div>
    <!-- 商家店铺信息头部 -->
    <div class="my-shop-header" v-if="myShopInfo && myShopInfo.auditStatus === '1'">
      <h2>我的店铺：{{ myShopInfo.shopName }}
        <el-tag :type="myShopInfo.status === '0' ? 'success' : 'danger'" class="status-badge">
          {{ myShopInfo.status === '0' ? '营业中' : '已停业' }}
        </el-tag>
      </h2>
      <el-button type="primary" size="mini" style="float: right;" @click="handleEditShop">
        <i class="el-icon-edit"></i> 编辑店铺信息
      </el-button>
    </div>

    <!-- 店铺状态面板 -->
    <div v-if="myShopInfo" class="shop-status-panel">
      <div class="shop-status-content">
        <h3>店铺状态</h3>
        <p v-if="myShopInfo.auditStatus === '1'">
          您的店铺已通过审核，可以开始添加商品和管理店铺了。
          <span v-if="myShopInfo.auditTime">
            （审核通过时间：{{ myShopInfo.auditTime.replace('T', ' ').substring(0, 19) }}）
          </span>
        </p>
        <p v-else-if="myShopInfo.auditStatus === '0'">您的店铺正在等待审核，暂时无法添加商品。</p>
        <p v-else-if="myShopInfo.auditStatus === '2'">您的店铺审核未通过，请修改后重新提交。</p>
      </div>
      <div class="shop-status-actions" v-if="myShopInfo.auditStatus === '2'">
        <el-button type="primary" @click="handleEditShop">修改店铺信息</el-button>
      </div>
    </div>
    <!-- 提示商家创建店铺（如果还没有店铺） -->
    <div v-if="!myShopInfo" class="no-shop-reminder">
      <el-card>
        <div slot="header">
          <h3>您还没有创建店铺</h3>
        </div>
        <div style="text-align: center; padding: 30px 0;">
          <p style="margin-bottom: 20px;">创建店铺后，您可以开始添加和管理您的商品</p>
          <el-button type="primary" @click="handleAddShop">立即创建店铺</el-button>
        </div>
      </el-card>
    </div>
    <!-- 商品管理区域（只有存在店铺时显示） -->
    <div v-if="myShopInfo && myShopInfo.auditStatus === '1'">
      <!-- 商品搜索和操作区域 -->
      <el-row class="search-bar">
        <el-col :span="8">
          <el-input
                  v-model="productSearchForm.productName"
                  placeholder="请输入商品名称搜索"
                  @keyup.enter.native="loadMyProducts"
                  clearable>
            <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="loadMyProducts">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="16" style="text-align: right;">
          <el-button
                  type="primary"
                  icon="el-icon-plus"
                  @click="handleAddNewProduct">
            添加新商品
          </el-button>
        </el-col>
      </el-row>

      <!-- 我的商品列表 -->
      <el-table
              :data="myProductList"
              style="width: 100%"
              :header-cell-style="{background: '#f5f7fa'}"
              border
              ref="productTable">
        <el-table-column
                type="index"
                label="序号"
                width="60">
        </el-table-column>
        <el-table-column
                prop="productId"
                label="商品ID"
                width="100">
        </el-table-column>
        <el-table-column
                prop="productCode"
                label="商品编码"
                width="120">
        </el-table-column>
        <el-table-column
                prop="productName"
                label="商品名称"
                width="150">
        </el-table-column>
        <el-table-column
                prop="category.categoryName"
                label="分类名称"
                width="120">
        </el-table-column>
        <el-table-column
                prop="unit.unitName"
                label="单位名称"
                width="100">
        </el-table-column>
        <el-table-column
                prop="brand.brandName"
                label="品牌名称"
                width="120">
        </el-table-column>
        <el-table-column
                prop="variety.varietyName"
                label="品种名称"
                width="120">
        </el-table-column>
        <el-table-column
                prop="origin.originName"
                label="产地名称"
                width="120">
        </el-table-column>
        <el-table-column
                prop="grade.gradeName"
                label="等级名称"
                width="120">
        </el-table-column>
        <el-table-column
                prop="cold.coldName"
                label="冷藏方式"
                width="120">
        </el-table-column>
        <el-table-column
                label="规格信息"
                width="180">
          <template slot-scope="scope">
            <div v-if="getSpecData(scope.row.specJson)">
              <div>规格：{{ getSpecData(scope.row.specJson).specName }}</div>
              <div>值：{{ getSpecData(scope.row.specJson).specValue }}</div>
            </div>
            <div v-else>无规格</div>
          </template>
        </el-table-column>
        <el-table-column
                prop="minOrderQuantity"
                label="最小起订量"
                width="100">
        </el-table-column>
        <el-table-column
                prop="price"
                label="参考价格"
                width="100">
        </el-table-column>
        <el-table-column
                prop="imageUrl"
                label="商品图片"
                width="120">
          <template slot-scope="scope">
            <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" style="width: 50px; height: 50px; object-fit: cover;">
          </template>
        </el-table-column>
        <el-table-column
                prop="description"
                label="商品描述"
                width="150"
                show-overflow-tooltip>
        </el-table-column>
        <el-table-column
                prop="status"
                label="状态"
                width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
                prop="delFlag"
                label="删除标志"
                width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.delFlag === '0' ? 'success' : 'danger'">
              {{ scope.row.delFlag === '0' ? '存在' : '删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
                prop="createBy"
                label="创建者"
                width="100">
        </el-table-column>
        <el-table-column
                prop="createTime"
                label="创建时间"
                width="160">
          <template slot-scope="scope">
            {{ scope.row.createTime ? scope.row.createTime.replace('T', ' ').substring(0, 19) : '' }}
          </template>
        </el-table-column>
        <el-table-column
                prop="updateBy"
                label="更新者"
                width="100">
        </el-table-column>
        <el-table-column
                prop="updateTime"
                label="更新时间"
                width="160">
          <template slot-scope="scope">
            {{ scope.row.updateTime ? scope.row.updateTime.replace('T', ' ').substring(0, 19) : '' }}
          </template>
        </el-table-column>
        <el-table-column
                prop="remark"
                label="备注"
                width="120"
                show-overflow-tooltip>
        </el-table-column>
        <el-table-column
                label="操作"
                fixed="right"
                width="150">
          <template slot-scope="scope">
            <el-button
                    size="mini"
                    @click="handleEditProduct(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 商品列表分页 -->
      <el-pagination
              @size-change="handleProductSizeChange"
              @current-change="handleProductCurrentChange"
              :current-page="productCurrentPage"
              :page-sizes="[5,10,15,20]"
              :page-size="productPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="productTotal"
              style="margin-top: 15px; text-align: right;">
      </el-pagination>
    </div>

    <!-- 店铺信息编辑对话框 -->
    <el-dialog :title="shopDialogTitle" :visible.sync="shopDialogVisible" width="600px">
      <el-form :model="shopForm" :rules="shopRules" ref="shopForm" label-width="120px">
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="shopForm.shopName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺LOGO" prop="shopLogo">
          <el-upload
                  class="upload-demo"
                  action="/vegetablemarketexpress/shop/uploadShopLogoImage"
                  name="pic"
                  :on-success="handleLogoUploadSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeImageUpload"
                  :limit="1"
                  :file-list="logoFileList"
                  list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
          <el-input v-model="shopForm.shopLogo" type="hidden"></el-input>
          <div v-if="shopForm.shopLogo">
            <img :src="shopForm.shopLogo" style="width: 100px; height: 100px; margin-top: 10px;" />
          </div>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="shopForm.contactPhone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺地址" prop="shopAddress">
          <el-input v-model="shopForm.shopAddress" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="经营类型" prop="businessType">
          <el-input v-model="shopForm.businessType" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="截单时间" prop="cutOffTime">
          <el-input v-model="shopForm.cutOffTime" placeholder="例如: 18:00" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺状态" prop="status">
          <el-radio-group v-model="shopForm.status">
            <el-radio label="0">营业中</el-radio>
            <el-radio label="1">已停业</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="shopForm.remark" autocomplete="off" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicence">
          <el-upload
                  class="upload-demo"
                  action="/vegetablemarketexpress/shop/uploadBusinessLicenceImage"
                  name="pic"
                  :on-success="handleBusinessLicenceSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeImageUpload"
                  :limit="1"
                  :file-list="businessLicenceFileList"
                  list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
          <el-input v-model="shopForm.businessLicence" type="hidden"></el-input>
          <div v-if="shopForm.businessLicence">
            <img :src="shopForm.businessLicence" style="width: 100px; height: 100px; margin-top: 10px;" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shopDialogVisible = false">取 消</el-button>
        <el-button @click="resetShopForm('shopForm')">重置</el-button>
        <el-button type="primary" @click="submitShopForm('shopForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加/更新商品对话框 (与shop.html保持一致) -->
    <el-dialog :title="productDialogTitle" :visible.sync="productDialogVisible" width="800px">
      <el-form :model="productForm" :rules="productRules" ref="productForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编码" prop="productCode">
              <el-input v-model="productForm.productCode" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="productForm.productName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId">
              <el-select v-model="productForm.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                        v-for="item in categoryList"
                        :key="item.categoryId"
                        :label="item.categoryName"
                        :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品单位" prop="unitId">
              <el-select v-model="productForm.unitId" placeholder="请选择单位" style="width: 100%">
                <el-option
                        v-for="item in unitList"
                        :key="item.unitId"
                        :label="item.unitName"
                        :value="item.unitId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品品牌" prop="brandId">
              <el-select v-model="productForm.brandId" placeholder="请选择品牌" style="width: 100%">
                <el-option
                        v-for="item in brandList"
                        :key="item.brandId"
                        :label="item.brandName"
                        :value="item.brandId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 在品牌选择后添加品种选择 -->
          <el-col :span="12">
            <el-form-item label="商品品种" prop="varietyId">
              <el-select v-model="productForm.varietyId" placeholder="请选择品种" style="width: 100%">
                <el-option
                        v-for="item in varietyList"
                        :key="item.varietyId"
                        :label="item.varietyName"
                        :value="item.varietyId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 添加产地选择 -->
          <el-col :span="12">
            <el-form-item label="商品产地" prop="originId">
              <el-select v-model="productForm.originId" placeholder="请选择产地" style="width: 100%">
                <el-option
                        v-for="item in originList"
                        :key="item.originId"
                        :label="item.originName"
                        :value="item.originId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 添加等级选择 -->
          <el-col :span="12">
            <el-form-item label="商品等级" prop="gradeId">
              <el-select v-model="productForm.gradeId" placeholder="请选择等级" style="width: 100%">
                <el-option
                        v-for="item in gradeList"
                        :key="item.gradeId"
                        :label="item.gradeName"
                        :value="item.gradeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 添加冷藏方式选择 -->
          <el-col :span="12">
            <el-form-item label="冷藏方式" prop="coldId">
              <el-select v-model="productForm.coldId" placeholder="请选择冷藏方式" style="width: 100%">
                <el-option
                        v-for="item in coldList"
                        :key="item.coldId"
                        :label="item.coldName"
                        :value="item.coldId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品规格" prop="specId">
              <el-select v-model="selectedSpecId" placeholder="请选择规格" style="width: 100%" @change="handleSpecChange">
                <el-option
                        v-for="item in specList"
                        :key="item.specId"
                        :label="item.specName"
                        :value="item.specId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="selectedSpecValues.length > 0">
            <el-form-item label="规格值" prop="specValue">
              <el-select v-model="selectedSpecValue" placeholder="请选择规格值" style="width: 100%">
                <el-option
                        v-for="value in selectedSpecValues"
                        :key="value"
                        :label="value"
                        :value="value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小起订量" prop="minOrderQuantity">
              <el-input v-model="productForm.minOrderQuantity" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参考价格" prop="price">
              <el-input v-model="productForm.price" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="productForm.status" style="width: 100%">
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="删除标志" prop="delFlag">
              <el-select v-model="productForm.delFlag" style="width: 100%">
                <el-option label="存在" value="0"></el-option>
                <el-option label="删除" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品图片">
          <el-upload
                  class="upload-demo"
                  action="/vegetablemarketexpress/product/uploadProductImage"
                  name="pic"
                  :on-success="handleImageSuccess"
                  :on-error="handleImageError"
                  :before-upload="beforeImageUpload"
                  :limit="1"
                  :file-list="imageFileList"
                  list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
          <el-input v-model="productForm.imageUrl" type="hidden"></el-input>
          <div v-if="productForm.imageUrl">
            <img :src="productForm.imageUrl" style="width: 100px; height: 100px; margin-top: 10px;" />
          </div>
        </el-form-item>

        <el-form-item label="商品描述">
          <el-input type="textarea" v-model="productForm.description" autocomplete="off" :rows="3"></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="productForm.remark" autocomplete="off" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false">取 消</el-button>
        <el-button @click="resetProductForm('productForm')">重置</el-button>
        <el-button type="primary" @click="submitProductForm('productForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        // 店铺相关数据
        myShopInfo: null,               // 商家自己的店铺信息
        shopDialogVisible: false,       // 店铺对话框是否可见
        shopDialogTitle: '创建店铺',    // 店铺对话框标题
        shopForm: {                     // 店铺表单数据
          shopId: '',
          shopName: '',
          shopLogo: '',
          contactPhone: '',
          shopAddress: '',
          businessType: '',
          cutOffTime: '',
          status: '0',                  // 默认营业中
          remark: '',
          businessLicence: ''
        },
        shopRules: {
          shopName: [
            { required: true, message: '请输入店铺名称', trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' }
          ],
          shopAddress: [
            { required: true, message: '请输入店铺地址', trigger: 'blur' }
          ],
          businessLicence: [
            { required: true, message: '请上传营业执照', trigger: 'change' }
          ]
        },
        logoFileList: [],               // 店铺LOGO文件列表
        businessLicenceFileList: [],    // 营业执照文件列表

        // 商品相关数据
        myProductList: [],              // 商家自己的商品列表
        productSearchForm: {            // 商品搜索表单
          productName: ''
        },
        productCurrentPage: 1,          // 商品列表当前页码
        productPageSize: 10,            // 商品列表每页条数
        productTotal: 0,                // 商品总数
        productDialogVisible: false,    // 商品对话框是否可见
        productDialogTitle: '添加商品', // 商品对话框标题
        productForm: {                  // 商品表单数据
          productId: '',
          productCode: '',
          productName: '',
          categoryId: '',
          unitId: '',
          brandId: '',
          varietyId: '',
          originId: '',
          gradeId: '',
          coldId: '',
          specId: '', // 规格ID（用于关联，非JSON字段）
          minOrderQuantity: '',
          price: '',
          imageUrl: '',
          description: '',
          status: '0',
          delFlag: '0',
          createBy: '',
          createTime: '',
          updateBy: '',
          updateTime: '',
          remark: ''
        },
        productRules: {
          productCode: [
            { required: true, message: '请输入商品编码', trigger: 'blur' }
          ],
          productName: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          categoryId: [
            { required: true, message: '请选择商品分类', trigger: 'change' }
          ],
          unitId: [
            { required: true, message: '请选择商品单位', trigger: 'change' }
          ],
          brandId: [
            { required: true, message: '请选择商品品牌', trigger: 'change' }
          ],
          originId: [
            { required: true, message: '请选择商品产地', trigger: 'change' }
          ],
          gradeId: [
            { required: true, message: '请选择商品等级', trigger: 'change' }
          ],
          coldId: [
            { required: true, message: '请选择冷藏方式', trigger: 'change' }
          ],
          price: [
            { required: true, message: '请输入参考价格', trigger: 'blur' }
          ]
        },

        // 属性列表数据（与shop.html保持一致）
        categoryList: [],
        brandList: [],
        unitList: [],
        specList: [],
        varietyList: [],// 商品种类列表
        originList: [], // 产地列表
        gradeList: [],  // 等级列表
        coldList: [],   // 冷藏方式列表
        selectedSpecId: '', // 选中的规格ID
        selectedSpecValues: [], // 选中的规格值列表
        selectedSpecValue: '', // 选中的规格值
        imageFileList: [],// 图片文件列表
      }
    },
    created() {
      // 页面加载时获取商家自己的店铺信息
      this.getMyShopInfo();
      // 加载所有下拉列表数据
      this.loadCategoryList();
      this.loadBrandList();
      this.loadUnitList();
      this.loadSpecList();
      this.loadVarietyList();
      this.loadOriginList();
      this.loadGradeList();
      this.loadColdList();
    },
    methods: {
      /**
       * 获取商家自己的店铺信息
       */
      getMyShopInfo() {
        let _this = this;
        axios.get('/vegetablemarketexpress/shop/getMyShop', {
          withCredentials: true // 确保携带登录状态
        })
                .then(function (response) {
                  if (response.data.code == 200) {
                    _this.myShopInfo = response.data.data;
                    // 如果有店铺，加载店铺的商品
                    if (_this.myShopInfo) {
                      _this.loadMyProducts();
                    }
                  } else {
                    // 没有店铺信息时，返回空
                    _this.myShopInfo = null;
                    // 处理特定异常：例如"非商家角色"
                    if (response.data.msg.includes('不是商家')) {
                      _this.$message.warning('您不是商家角色，无法创建店铺');
                    }
                  }
                })
                .catch(function (error) {
                  console.log(error);
                  // 处理401未登录
                  if (error.response && error.response.status === 401) {
                    _this.$message.error('用户未登录，请重新登录');
                    window.location.href = '/login.html';
                    return;
                  }
                  _this.$message.error('获取店铺信息失败');
                });
      },

      /**
       * 加载商家自己的商品列表
       */
      loadMyProducts() {
        if (!this.myShopInfo || !this.myShopInfo.shopId) {
          return;
        }
        this.loading = true;
        let _this = this;
        // 1. 先调用ShopProductController获取当前店铺关联的商品ID列表
        axios.post('/vegetablemarketexpress/shopProduct/selectProductIdsByShopId',null, {
                  params: { // 使用params传递参数
                    shopId: this.myShopInfo.shopId
                  }
                },
                {
                  headers: {
                    'Content-Type': 'application/json' // 明确指定Content-Type
                  }
                }).then(function (productIdsRes) {
          console.log('获取商品ID列表响应:', productIdsRes.data);
          if (productIdsRes.data.code == 200) {
            const productIds = productIdsRes.data.data;
            console.log('商品ID列表:', productIds);
            if (productIds.length === 0) {
              _this.myProductList = [];
              _this.productTotal = 0;
              _this.loading = false;
              _this.$message.info('该店铺暂无商品');
              return;
            }
            // 2. 使用单个查询接口逐个查询
            const productPromises = productIds.map(productId => {
              return axios.get(`/vegetablemarketexpress/product/selectProductById?productId=${productId}`)
                      .then(response => {
                        if (response.data.code == 200) {
                          return response.data.data;
                        }
                        return null;
                      })
                      .catch(error => {
                        console.error(`商品ID ${productId} 查询异常:`, error);
                        return null;
                      });

            });
            // 等待所有查询完成
            Promise.all(productPromises)
                    .then(products => {
                      // 过滤掉查询失败的商品
                      _this.myProductList = products.filter(product => product !== null);
                      _this.productTotal = _this.myProductList.length;
                    })
                    .catch(error => {
                      console.error('商品查询异常:', error);
                      _this.$message.error('加载商品列表失败');
                    })
                    .finally(() => {
                      _this.loading = false;
                    });
          } else {
            _this.$message.error('获取商品ID列表失败: ' + productIdsRes.data.msg);
            _this.loading = false;
          }
        }).catch(function (error) {
          console.error('查询店铺关联商品ID异常:', error);
          _this.$message.error('加载商品列表失败');
          _this.loading = false;
        });
      },

      // 从JSON中提取规格名称
      getSpecData(specJson) {
        if (!specJson) return null;
        try {
          const spec = JSON.parse(specJson);
          // 确保返回的字段与提交时一致（specName + specValue）
          return {
            specName: spec.specName || '未知规格',
            specValue: spec.specValue || '未选择值'
          };
        } catch (e) {
          console.error('解析规格JSON失败：', e);
          return null;
        }
      },

      // 规格选择变化事件
      handleSpecChange(specId) {
        const spec = this.specList.find(item => item.specId === specId);
        if (spec && spec.specValues) {
          try {
            this.selectedSpecValues = JSON.parse(spec.specValues);
          } catch (e) {
            this.selectedSpecValues = spec.specValues.split(',');
          }
        } else {
          this.selectedSpecValues = [];
        }
        this.selectedSpecValue = '';
      },

      // 加载分类列表
      loadCategoryList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/category/queryByPage', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.categoryList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      // 加载品牌列表
      loadBrandList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/brand/queryByPage', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.brandList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      // 加载单位列表
      loadUnitList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/unit/queryByPage', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.unitList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      // 加载规格列表
      loadSpecList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/spec/queryByPage', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.specList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      // 加载品种列表
      loadVarietyList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/variety/queryByParam', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.varietyList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      // 加载产地列表
      loadOriginList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/origin/listByPage', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.originList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      // 加载等级列表
      loadGradeList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/grade/listByPage', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.gradeList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      // 加载冷藏方式列表
      loadColdList() {
        let _this = this;
        axios.post('/vegetablemarketexpress/cold/listByPage', {
          "pageNo": 1,
          "pageSize": 1000,
          "data": { status: '0', delFlag: '0' }
        }).then(function (response) {
          if (response.data.code==200) {
            _this.coldList = response.data.data.list;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      /**
       * 打开添加店铺对话框
       */
      handleAddShop() {
        this.shopDialogVisible = true;
        this.shopDialogTitle = '创建店铺';
        this.shopForm = {
          shopId: '',
          shopName: '',
          shopLogo: '',
          contactPhone: '',
          shopAddress: '',
          businessType: '',
          cutOffTime: '',
          status: '0',
          remark: '',
          businessLicence: ''
        };
        this.logoFileList = [];
        this.businessLicenceFileList = [];
      },

      /**
       * 打开编辑店铺对话框
       */
      handleEditShop() {
        this.shopDialogVisible = true;
        this.shopDialogTitle = '编辑店铺信息';
        this.shopForm = JSON.parse(JSON.stringify(this.myShopInfo));

        // 处理店铺LOGO
        if (this.shopForm.shopLogo) {
          const fileName = this.shopForm.shopLogo.substring(this.shopForm.shopLogo.lastIndexOf('/') + 1);
          this.logoFileList = [{
            name: fileName,
            url: this.shopForm.shopLogo
          }];
        }

        // 处理营业执照
        if (this.shopForm.businessLicence) {
          const fileName = this.shopForm.businessLicence.substring(this.shopForm.businessLicence.lastIndexOf('/') + 1);
          this.businessLicenceFileList = [{
            name: fileName,
            url: this.shopForm.businessLicence
          }];
        }
      },

      /**
       * 提交店铺表单
       */
      submitShopForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let uri = '/vegetablemarketexpress/shop/insertShop'; // 对应后端ShopController的新增接口
            if (this.shopForm.shopId) {
              uri = '/vegetablemarketexpress/shop/updateShop'; // 对应后端的修改接口
            }

            let _this = this;
            let submitForm = JSON.parse(JSON.stringify(this.shopForm));

            axios.post(uri, submitForm)
                    .then(function (response) {
                      if (response.data.code == 200) {
                        _this.$message({
                          message: '操作成功',
                          type: 'success'
                        });
                        // 重新获取店铺信息
                        _this.getMyShopInfo();
                        _this.shopDialogVisible = false;
                      } else {
                        _this.$message.error('操作失败: ' + response.data.msg);
                      }
                    })
                    .catch(function (error) {
                      console.log(error);
                      _this.$message.error('操作异常');
                    });
          } else {
            this.$message.error('表单验证失败');
          }
        });
      },

      /**
       * 重置店铺表单
       */
      resetShopForm(formName) {
        this.$refs[formName].resetFields();
      },

      /**
       * 打开添加商品对话框
       */
      handleAddNewProduct() {
        // 校验：商家必须已创建店铺，且 shopId 有效
        if (!this.myShopInfo || !this.myShopInfo.shopId) {
          this.$message.error('请先创建店铺，再添加商品');
          return; // 阻止后续操作
        }
        this.productDialogVisible = true;
        this.productDialogTitle = '添加新商品';
        this.productForm = {
          productId: '',
          productCode: '',
          productName: '',
          categoryId: '',
          unitId: '',
          brandId: '',
          varietyId: '',
          originId: '',
          gradeId: '',
          coldId: '',
          specId: '',
          minOrderQuantity: '',
          price: '',
          imageUrl: '',
          description: '',
          status: '0',
          delFlag: '0',
          createBy: '',
          createTime: '',
          updateBy: '',
          updateTime: '',
          remark: ''
        };
        // 清空规格选择
        this.selectedSpecId = '';
        this.selectedSpecValues = [];
        this.selectedSpecValue = '';
        // 清空文件列表
        this.imageFileList = [];
      },

      /**
       * 打开编辑商品对话框
       */
      handleEditProduct(index, row) {
        this.productDialogVisible = true;
        this.productDialogTitle = "修改商品";
        this.productForm = JSON.parse(JSON.stringify(row));
        // 清空规格选择
        this.selectedSpecId = '';
        this.selectedSpecValues = [];
        this.selectedSpecValue = '';
        // 如果已有图片，初始化文件列表用于预览
        if (this.productForm.imageUrl) {
          const fileName = this.productForm.imageUrl.substring(this.productForm.imageUrl.lastIndexOf('/') + 1);
          this.imageFileList = [{
            name: fileName,
            url: this.productForm.imageUrl
          }];
        }
        // 解析规格JSON
        if (row.specJson) {
          try {
            const specData = JSON.parse(row.specJson);
            this.selectedSpecId = specData.specId || '';
            this.selectedSpecValue = specData.specValue || '';

            // 加载对应的规格值
            if (this.selectedSpecId) {
              this.handleSpecChange(this.selectedSpecId);
            }
          } catch (e) {
            console.error('解析规格JSON失败:', e);
          }
        }
      },

      /**
       * 提交商品表单
       */
      submitProductForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let _this = this;
            let submitForm = JSON.parse(JSON.stringify(this.productForm));

            // 处理规格JSON数据
            if (this.selectedSpecId && this.selectedSpecValue) {
              const selectedSpec = this.specList.find(item => item.specId === this.selectedSpecId);
              if (selectedSpec) {
                submitForm.specJson = JSON.stringify({
                  specId: this.selectedSpecId,
                  specName: selectedSpec.specName,
                  specValue: this.selectedSpecValue
                });
              }
            }

            // 转换数值类型
            if (submitForm.categoryId) submitForm.categoryId = parseInt(submitForm.categoryId);
            if (submitForm.unitId) submitForm.unitId = parseInt(submitForm.unitId);
            if (submitForm.brandId) submitForm.brandId = parseInt(submitForm.brandId);
            if (submitForm.varietyId) submitForm.varietyId = parseInt(submitForm.varietyId);
            if (submitForm.originId) submitForm.originId = parseInt(submitForm.originId);
            if (submitForm.gradeId) submitForm.gradeId = parseInt(submitForm.gradeId);
            if (submitForm.coldId) submitForm.coldId = parseInt(submitForm.coldId);
            if (submitForm.specId) submitForm.specId = parseInt(submitForm.specId);
            if (submitForm.price) submitForm.price = parseFloat(submitForm.price);
            if (submitForm.minOrderQuantity) submitForm.minOrderQuantity = parseFloat(submitForm.minOrderQuantity);

            // 判断是新增还是更新
            if (this.productDialogTitle === '添加新商品') {
              // 新增商品并自动关联到店铺
              this.addProductAndLinkToShop(submitForm);
            } else {
              // 更新商品
              this.updateProduct(submitForm);
            }
          } else {
            this.$message.error('表单验证失败');
          }
        });
      },

      /**
       * 新增商品并关联到店铺
       */
      addProductAndLinkToShop(productData) {
        let _this = this;

        // 1. 先添加商品
        axios.post('/vegetablemarketexpress/product/insertProduct', productData)
                .then(function (response) {
                  console.log('商品添加响应:', response.data);
                  if (response.data.code == 200) {
                    const newProduct = response.data.data;
                    _this.$message.success('商品添加成功');
                    console.log('新商品信息:', newProduct);

                    // 2. 将商品关联到当前店铺 - 修复参数传递方式
                    const formData = new URLSearchParams();
                    formData.append('shopId', _this.myShopInfo.shopId);
                    formData.append('productId', newProduct.productId);

                    console.log('关联参数:', {
                      shopId: _this.myShopInfo.shopId,
                      productId: newProduct.productId
                    });

                    return axios.post('/vegetablemarketexpress/shopProduct/addProductToMyShop', formData, {
                      headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                      }
                    });
                  } else {
                    throw new Error(response.data.msg || '商品添加失败');
                  }
                })
                .then(function (linkResponse) {
                  console.log('关联店铺响应:', linkResponse.data);
                  if (linkResponse.data.code == 200) {
                    _this.$message.success('商品已成功关联到您的店铺');
                    _this.loadMyProducts(); // 重新加载商品列表
                    _this.productDialogVisible = false;
                  } else {
                    throw new Error(linkResponse.data.msg || '商品关联店铺失败');
                  }
                })
                .catch(function (error) {
                  console.error('添加商品并关联店铺失败:', error);
                  _this.$message.error('操作失败: ' + (error.message || '未知错误'));
                });
      },

      /**
       * 更新商品
       */
      updateProduct(productData) {
        let _this = this;

        axios.post('/vegetablemarketexpress/product/updateProduct', productData)
                .then(function (response) {
                  if (response.data.code == 200) {
                    _this.$message.success('商品更新成功');
                    _this.loadMyProducts(); // 重新加载商品列表
                    _this.productDialogVisible = false;
                  } else {
                    throw new Error(response.data.msg || '商品更新失败');
                  }
                })
                .catch(function (error) {
                  console.error('更新商品失败:', error);
                  _this.$message.error('操作失败: ' + (error.message || '未知错误'));
                });
      },

      /**
       * 重置商品表单
       */
      resetProductForm(formName) {
        this.$refs[formName].resetFields();
        this.selectedSpecId = '';
        this.selectedSpecValues = [];
        this.selectedSpecValue = '';
      },

      /**
       * 删除商品
       */
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let _this = this;
          axios.delete('/vegetablemarketexpress/product/deleteProductById?productId=' + row.productId)
                  .then(function (response) {
                    if (response.data.code == 200) {
                      _this.$message({
                        message: '删除成功',
                        type: 'success'
                      });
                      _this.loadMyProducts();
                    } else {
                      _this.$message.error('删除失败: ' + response.data.msg);
                    }
                  })
                  .catch(function (error) {
                    console.log(error);
                    _this.$message.error('删除异常');
                  });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      /**
       * 商品列表分页大小改变
       */
      handleProductSizeChange(val) {
        this.productPageSize = val;
        this.productCurrentPage = 1;
        this.loadMyProducts();
      },

      /**
       * 商品列表当前页改变
       */
      handleProductCurrentChange(val) {
        this.productCurrentPage = val;
        this.loadMyProducts();
      },

      /**
       * 图片上传前处理
       */
      beforeImageUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt5M = file.size / 1024 / 1024 < 5;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/PNG 格式!');
          return false;
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 5MB!');
          return false;
        }
        return true;
      },

      /**
       * 商品图片上传成功处理
       */
      handleImageSuccess(response, file, fileList) {
        if (response.code === 200) {
          // 后端返回 {filePath: "图片地址", originName: "原文件名"}
          this.productForm.imageUrl = response.data.filePath;
          this.$message.success('商品图片上传成功');
        } else {
          this.$message.error('商品图片上传失败: ' + (response.msg || '未知错误'));
        }
      },

      /**
       * 图片上传失败处理
       */
      handleImageError(err, file, fileList) {
        this.$message.error('商品图片上传失败: ' + err);
      },

      /**
       * 店铺LOGO上传成功回调
       */
      handleLogoUploadSuccess(response) {
        if (response.code === 200) {
          // 后端返回 {filePath: "图片地址", originName: "原文件名"}
          this.shopForm.shopLogo = response.data.filePath;
          this.$message.success('店铺LOGO上传成功');
        } else {
          this.$message.error('店铺LOGO上传失败: ' + (response.msg || '未知错误'));
        }
      },

      /**
       * 营业执照上传成功回调
       */
      handleBusinessLicenceSuccess(response) {
        if (response.code === 200) {
          // 后端返回 {filePath: "图片地址", originName: "原文件名"}
          this.shopForm.businessLicence = response.data.filePath;
          this.$message.success('营业执照上传成功');
        } else {
          this.$message.error('营业执照上传失败: ' + (response.msg || '未知错误'));
        }
      },

      /**
       * 上传失败回调
       */
      handleUploadError(error) {
        console.log(error);
        this.$message.error('文件上传失败，请重试');
      }
    }
  });
</script>
</body>
</html>
